// 解决 click 事件的 300ms 延迟的问题
FastClick.attach(document.body)

!(async function(){
  const musicBox = document.querySelector('.music-box'),
        disBox = musicBox.querySelector('.dis-box'),
        dis = musicBox.querySelector('.dis'),
        playButton = document.querySelector('.play-box'),
        lyricBox = document.querySelector('.lyric-box'),
        tit = lyricBox.querySelector('.title'),
        audioBox = document.querySelector('#audioBox'),
        markImage = document.querySelector('.mark-image')
  let wrapper,
      wrapperList = [],   // 记录每一条歌词及时间
      timer = null,
      lyricNum = 0  // 记录歌词数量
      
  
  
  // 时间转换
  const format = function format(time){
    if(isNaN(time)) return
    let minutes = Math.floor(time/60),
        seconds = Math.round(time%60)
    minutes = minutes>9?minutes+'':'0'+minutes
    seconds = seconds>9?seconds+'':'0'+seconds

    return {
      minutes,
      seconds
    }
  }

  // 音乐结束
  const playend = function playend(){
    clearInterval(timer)
    timer = null
    playButton.style.display = 'block'
    disBox.style.animationPlayState = 'paused'
    wrapper.style.transform = 'translateY(0)'
    matchNum = 0
    
  }
  
  // 音乐控制
  const handle = function handle(){
      // currentTime:存储了当前播放的时间「单位秒」
      // duration:存储了总的时间
      let { currentTime,duration} = audioBox
      if(isNaN(currentTime) || isNaN(duration)) return

      if(currentTime>=duration){
        playend()
        return
      }

      let {minutes:bgmMin,seconds:bgmSec} = format(currentTime)      
      
      let matchs = wrapperList.filter(item=>{
        let LyrMin = item.getAttribute('minutes'),
            LyrSec = item.getAttribute('seconds')
        return LyrMin === bgmMin && LyrSec === bgmSec
      })

      if(matchs.length > 0){
        let pH = wrapperList[0].offsetHeight
        lyricNum+= matchs.length
        if(lyricNum >= 1){
          let offset = (lyricNum-1)*pH
          wrapper.style.transform = `translateY(-${offset}px)`
        }
        
      }
      
      
  }

  musicBox.addEventListener('click',function(e){
    // 如果是暂停状态
    if(audioBox.paused){
      audioBox.play()
      playButton.style.display = 'none'
      disBox.style.animationPlayState = 'running'
      handle()
      // 歌词移动
      if(!timer) timer = setInterval(handle,1000)
      return
    }
    // 如果是播放状态
    audioBox.pause()
    playButton.style.display = 'block'
    disBox.style.animationPlayState = 'paused'

    clearInterval(timer)
    timer = null
    
  })

  
  // 歌词处理
  const bindingLyric = function bindingLyric(lyric){
    let arr = []
    lyric.replace(/\[(\d+):(\d+.?\d+)\](.+)\n/g, (_, $1, $2, $3) => {
        arr.push({
            minutes: $1,
            seconds: Math.round($2)<10?'0'+Math.round($2):''+Math.round($2),
            text: $3.trim()
        })
    }) 

    let str = ``
    arr.forEach(({minutes,seconds,text})=>{
      str += `
        <p minutes=${minutes} seconds=${seconds}>${text}</p>
      `
    })

    return str
  }

  // 绑定数据
  const binding = function binding(data){
    const {title,duration,pic,audio,lyric} = data
    
    // @1 绑定基础信息
    dis.innerHTML = `<img src="${pic}" alt="">`
    markImage.style.backgroundImage = `url('${pic}')`
    audioBox.setAttribute('src',audio)

    // @2 歌词处理
    lyricBox.innerHTML = `
      <h2 class="title">${title}</h2>
      <div class="text">
        <div class="wrapper">
          ${bindingLyric(lyric)}
        </div>
      </div>
    `
    wrapper = lyricBox.querySelector('.wrapper')
    wrapperList = Array.from(wrapper.querySelectorAll('p'))
    
  }

  try{
    let { code,data } = await API.queryLyric()
      if(+code === 0){
        // 请求成功：网络层和业务层都成功
        binding(data)
        return
      }
  }catch(_){
    // 请求失败
   alert('网络繁忙，请刷新页面')
  }

})()
